const booklets = {}
let bookletsLength = 0
const fileEle = document.getElementById('file')
const submitEle = document.getElementById('submit')
fileEle.addEventListener('change', dealFile)
submitEle.addEventListener('click', submitBooklets)

const SERVICE_API_URL_PREFIX = 'http://192.168.1.105:3001/'  // 'http://localhost:3001/'

const container = document.getElementsByClassName('container')[0] 
const bookTotalEle = document.getElementsByClassName('book-total')[0] // 总书籍本书渲染元素
const previewBookletsBoxEle = document.getElementsByClassName('preview-booklets-box')[0] // 总书籍本书渲染元素
function renderPreviewBookletsBox() {
    let bookletCount = 1
    const previewBookletsBoxObjectInJs = new DocumentFragment()
    previewBookletsBoxObjectInJs.append(bookTotalEle)
    previewBookletsBoxObjectInJs.append(previewBookletsBoxEle)
    let previewBookletsBoxInnerHTML = '<h4 class="title">导入书籍名称预览</h4>' //
    for(let booklet in booklets) {
        previewBookletsBoxInnerHTML += `
            <div class="booklet-box"> <span>${bookletCount++}.</span> <span>${booklet}</span> </div>
        `
    }
    previewBookletsBoxEle.innerHTML = previewBookletsBoxInnerHTML //渲染
    bookTotalEle.innerHTML = `
        书籍数量：<span>${bookletsLength}</span> 本
    `
    container.append(previewBookletsBoxObjectInJs)
}

function dealFile(file) {
    let { files } = this
    files = Array.from(files)
    try {
        files.forEach((file)=>{
            const name = file.name
            const regexp = /([\S|\s]+).json$/
            const temp = name.match(regexp)
            if(!temp){
                throw new Error('文件格式必须为 json')
                return
            }
            const filename = temp[1]
            console.log('成功读取文件 ' + name)
            const fileReader = new FileReader()
            fileReader.readAsText(file)
            fileReader.onload = function () { 
                const data = fileReader.result
                //防止重复
                if(!booklets[filename]){
                    booklets[filename] = JSON.parse(data)
                    bookletsLength++
                    renderPreviewBookletsBox()
                }
            }
        })
    }catch(e) {
        alert(e.message)
    }
}

function submitBooklets() {
    console.log(bookletsLength + '本')
    $Ajax({
        url: SERVICE_API_URL_PREFIX + 'api/v1.0/booklets',
        method: 'POST',
        data: booklets,
        dataType: 'application/json; charset=utf-8',
        success(res) {
            res = JSON.parse(res)
            if(res.status === 'success') {
                alert(res.message + '\n确认后重新刷新')
                location.reload()
            }else {
                alert('导入失败')
            }
        }
    })
}